<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="课程介绍" prop="referra">
        <el-input v-model="queryParams.referra" placeholder="请输入课程介绍" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:nominate:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:nominate:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:nominate:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:nominate:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="nominateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="rid" />
      <el-table-column label="推荐名称" align="center" prop="name" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleFenPei(scope.row)" v-hasPermi="['system:nominate:remove']">分配课程</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:nominate:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:nominate:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改课程推荐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="推荐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入推荐名称" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="videoTitle" :visible.sync="videoDialog" width="900px" append-to-body :close-on-click-modal="false" fullscreen>
      <el-form :model="videoParams" ref="queryForm1" size="small" :inline="true" label-width="68px">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="videoParams.title" placeholder="请输入课程名称" clearable />
        </el-form-item>
        <el-form-item label="讲师" prop="Lecturer">
          <el-input v-model="videoParams.Lecturer" placeholder="请输入讲师" clearable />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <md-select-tree v-model="videoParams.categoryId" :defaultExpandAll="true" :data="parentList" nodeKey="rid" :defaultProps="{label:'name',children:'categoryList'}" placeholder="请选择上级"></md-select-tree>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isNominate">
          <el-select v-model="videoParams.isNominate" placeholder="是否推荐" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否首页" prop="isHome">
          <el-select v-model="videoParams.isHome" placeholder="是否首页" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="videoParams.status" placeholder="状态" clearable>
            <el-option label="显示" value="1"></el-option>
            <el-option label="隐藏" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getListVideo">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="videoResetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" ref="multipleTable" :data="videoList" height="60vh" row-key="rid"  @select="select"   >
        <el-table-column type="selection" :reserve-selection="true" width="55" align="left" />
        <el-table-column label="编号" align="left" prop="rid" width="50" />

        <el-table-column label="课程名称" align="left" prop="title" min-width="380" />

        <el-table-column label="讲师" align="left" prop="lecturer" />

        <el-table-column label="创建时间" align="left" prop="createTime" />
      </el-table>

      <pagination v-show="videoTotal>0" :total="videoTotal" :page.sync="videoParams.pageNum" :limit.sync="videoParams.pageSize" @pagination="getListVideo" />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFenPeiForm">分配</el-button>
        <el-button @click="cancelFenPei">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNominate, getNominate, delNominate, addNominate, updateNominate } from "@/api/web/nominate";
import { listNominateDetail, getNominateDetail, delNominateDetail, addNominateDetail, updateNominateDetail, distributionVideo } from "@/api/web/nominateDetails";
import { listVideo, getVideo, delVideo, addVideo, updateVideo, delZhangJie, delShiPin } from "@/api/web/video";
import { listCategory } from "@/api/web/category";
export default {
  name: "Nominate",
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程推荐表格数据
      nominateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        referra: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      videoDialog: false,
      videoTitle: null,
      videoParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        isNominate: null,
        isHome: null,
        status: null,
        Lecturer: null
      },
      videoList: [],
      videoTotal: 0,
      selectVideos: [],
      submitParams: {
        nominateId: null,
        detailDtos: []
      },
      parentList: []
    };
  },
  created () {
    this.getList();
    this.getParentList(true);
  },
  methods: {
    select(s,w){
      console.log(s,w,'w');
      console.log(this.selectVideos,'this.selectVideos');
      if(s.length==0){
        this.selectVideos=this.selectVideos.filter(item=>item !==w.rid)
      }else{
        this.selectVideos = [...new Set(s.map(m => { return m.rid }).concat(this.submitParams.detailDtos))]
      }
    },

    /** 查询课程推荐列表 */
    getList () {
      this.loading = true;
      listNominate(this.queryParams).then(response => {
        this.nominateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        rid: null,
        name: null,
        sort: 100,
        referra: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.rid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加课程推荐";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const rid = row.rid || this.ids
      getNominate(rid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程推荐";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.rid != null) {
            updateNominate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNominate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const rids = row.rid || this.ids;
      this.$modal.confirm('是否确认删除课程推荐编号为"' + rids + '"的数据项？').then(function () {
        return delNominate(rids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('zip/nominate/export', {
        ...this.queryParams
      }, `nominate_${new Date().getTime()}.xlsx`)
    },
    /** 分配 */
    async handleFenPei (row) {
      try {
        this.videoTitle = '分配课程'
        this.submitParams.nominateId = row.rid
        this.submitParams.detailDtos = []
        this.selectVideos = []

        // const res = await listNominateDetail({
        //   pageNum: 1,
        //   pageSize: 10000,
        //   nominateId: row.rid
        // })

        // if (res.rows && res.rows.length > 0) {
        //   this.submitParams.detailDtos = res.rows.map(m => { return m.videoId })
        //   this.selectVideos = this.submitParams.detailDtos
        // }

        this.videoDialog = true

        this.getListVideo()
      } catch (error) {
        console.log(error)
      }
    },
    /** 查询分类列表 */
    getParentList (flag) {
      this.categoryLoading = true
      listCategory({
        type: 1
      }).then(response => {
        this.parentList = response.data;
        if (!flag) {
          this.$nextTick(() => {
            setTimeout(() => {
              if (this.form.categoryId) {
                this.$refs.mdCategory.setCurrentKey(this.form.categoryId)
              }
              const nodesMap = this.$refs.mdCategory.store.nodesMap
              const keys = Object.keys(nodesMap)
              keys.forEach(key => {
                nodesMap[key].expanded = true
              })
              this.categoryLoading = false
            }, 500);
          })
        }
      });
    },
    async getListVideo () {
      this.loading = true
      try {
        const res = await listVideo(this.videoParams)
        this.videoList = res.rows;
        this.videoTotal = res.total;

        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection()
          if (this.selectVideos && this.selectVideos.length > 0) {
            this.selectVideos.forEach((id, index) => {
              const row = this.videoList.find(e => e.rid == id)
              if (row) {
                this.$refs.multipleTable.toggleRowSelection(row, true)
              } else {
                this.$refs.multipleTable.toggleRowSelection(row, false)
              }

              if (index === this.selectVideos.length - 1) {
                this.loading = false
              }
            })
          }
        })
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    // handleVideoTableSelectionChange (event) {
    //   this.selectVideos = [...new Set(event.map(m => { return m.rid }).concat(this.submitParams.detailDtos))]
    // },
    videoResetQuery () {
      this.resetForm("queryForm1")
      this.getListVideo()
    },
    async submitFenPeiForm () {
      try {
        if (this.selectVideos.length === 0) {
          this.$modal.msgWarning("请选择课程");
          return
        }

        this.submitParams.detailDtos = this.selectVideos.map(m => {
          return { videoId: m }
        })

        const res = await distributionVideo(this.submitParams)

        this.$modal.msgSuccess("分配成功")

        this.cancelFenPei()
      } catch (error) {
        console.log(error)
      }
    },
    cancelFenPei () {
      this.submitParams = {
        nominateId: null,
        detailDtos: []
      }
      this.selectVideos = []
      this.videoList = []
      this.videoTotal = 0
      this.videoParams = {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        title: null,
        isNominate: null,
        isHome: null,
        status: null,
        Lecturer: null
      }
      this.videoDialog = false
    }
  }
};
</script>
